#include "IIC.h"

static void iic_delay(void)
{
	for(uint32_t j=0;j<10;j++);
}


void iic_start(void)
{
	IIC_SDA(1);
	IIC_SCL(1);
	iic_delay();
	IIC_SDA(0);
	iic_delay();
	IIC_SCL(0);
	iic_delay();
}

void iic_stop(void)
{
	IIC_SDA(0);     
	iic_delay();
	IIC_SCL(1);
	iic_delay();
	IIC_SDA(1);    
	iic_delay();
}

void iic_ack(void)
{
	IIC_SDA(0);     
	iic_delay();
	IIC_SCL(1);     
	iic_delay();
	IIC_SCL(0);
	iic_delay();
	IIC_SDA(1);     
	iic_delay();
}

void iic_nack(void)
{
	IIC_SDA(1);     
	iic_delay();
	IIC_SCL(1);     
	iic_delay();
	IIC_SCL(0);
	iic_delay();
}

uint8_t iic_wait_ack(void)
{
	uint8_t waittime = 0;
	uint8_t rack = 0;

	IIC_SDA(1);    
	iic_delay();
	IIC_SCL(1);    
	iic_delay();

	while (IIC_READ_SDA)   
	{
		waittime++;

		if (waittime > 250)
		{
			iic_stop();
			rack = 1;
			break;
		}
	}
	IIC_SCL(0);    
	iic_delay();
	return rack;
}

uint8_t iic_read_byte(uint8_t ack)
{
	uint8_t i, receive = 0;

	for (i = 0; i < 8; i++ )    
	{
		receive <<= 1;  
		IIC_SCL(1);
		iic_delay();

		if (IIC_READ_SDA)
		{
			receive++;
		}
		
		IIC_SCL(0);
		iic_delay();
	}

	if (!ack)
	{
		iic_nack();     
	}
	else
	{
		iic_ack();     
	}

	return receive;
}

void iic_send_byte(uint8_t data)
{
	uint8_t t;
	
	for (t = 0; t < 8; t++)
	{
		IIC_SDA((data & 0x80) >> 7);    
		iic_delay();
		IIC_SCL(1);
		iic_delay();
		IIC_SCL(0);
		data <<= 1;     
	}
	IIC_SDA(1);       
}
